package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("upload")
    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
        log.info("上传的文件名: {}", file.getOriginalFilename());
        //String newFilename = generateUniqueFilename(file.getOriginalFilename());

        //保存本地磁盘上文件
        //file.transferTo(new File("D:\\" + newFilename));
        // 上传到阿里云
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        return Result.success(url);
    }

    /**
     * 生成一个唯一 的文件名
     * @param originalFilename
     * @return
     */
    private String generateUniqueFilename(String originalFilename) {
        String newFilename = UUID.randomUUID().toString().replace("-", "");
        //后缀名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return newFilename + extension;
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString().replace("-",""));
    }
}
